package org.example.algorithm.str;

import java.util.HashMap;
import java.util.Map;


//3. 无重复字符的最长子串
public class LengthOfLongestSubstringSolution {

    public static void main(String[] args) {
        String s = "tmmzuxt";
        LengthOfLongestSubstringSolution solution = new LengthOfLongestSubstringSolution();
        System.out.println(solution.lengthOfLongestSubstring(s));
    }

    /**
     * 双指针简化
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1) {
            return s.length();
        }
        int left = 0;
        int right = 0;
        int ans = 0;
        Map<Character, Integer> map = new HashMap<>();
        while (right < s.length()) {
            Character c = s.charAt(right);
            int lastPos = map.getOrDefault(c, -1);
            if (map.containsKey(c) && lastPos >= left) {
                ans = Math.max(ans, right-left);
                left = lastPos+1;
            } else if(right == s.length() - 1) {
                ans = Math.max(ans, right-left+1);
            }
            map.put(c, right);
            right++;
        }
        return ans;
    }
    /**
     * 双指针
     * @param s
     * @return
     */
    public static int lengthOfLongestSubstring2(String s) {
        int start = 0;
        int end = 0;
        int maxSubLen = 0;
        Map<Character, Integer> charMap = new HashMap<>();
        while (end < s.length()) {
            if (charMap.containsKey(s.charAt(end))) {
                int lastPos = charMap.get(s.charAt(end));
                while (start <= lastPos) {
                    charMap.remove(s.charAt(start));
                    start++;
                }
            } else {
                if (maxSubLen == 0) {
                    maxSubLen = end - start + 1;
                } else {
                    maxSubLen = Math.max(maxSubLen, end-start+1);
                }
            }
            charMap.put(s.charAt(end), end);
            end++;
        }
        return maxSubLen;
    }

    //效率较低
    public static int lengthOfLongestSubstring3(String s) {
        Map<Character, Integer> charMap = new HashMap<>();
        int start = 0;
        int maxSubstringLen = 0;
        for (int i=0;i<s.length();i++) {
            if (charMap.containsKey(s.charAt(i))) {
                start = charMap.get(s.charAt(i)) + 1;
                i = start;
                charMap = new HashMap<>();
            }
            charMap.put(s.charAt(i), i);
            if (maxSubstringLen == 0) {
                maxSubstringLen = i - start + 1;
            } else {
                maxSubstringLen = Math.max(maxSubstringLen, i-start+1);
            }
        }
        return maxSubstringLen;
    }
}
